/**
 * 专门处理 todos 的 reducer 函数
 */

import { nanoid } from "nanoid";

const initialState = [
  { id: 0, text: "吃饭", done: true, color: "" },
  { id: 1, text: "睡觉", done: false, color: "red" },
  { id: 2, text: "打豆豆", done: false, color: "blue" },
];

function todosReducer(prevState = initialState, action) {
  switch (action.type) {
    case "TODO_ADD":
      return [
        ...prevState,
        {
          // id: 3, // 写死了，后续注意
          id: nanoid(),
          text: action.text,
          done: false,
        },
      ];

    case "TODO_DEL":
      return prevState.filter((item) => {
        return item.id !== action.id;
      });

    case "TODO_CHANGE":
      return prevState.map((item) => {
        if (item.id === action.id) {
          return {
            ...item,
            done: !item.done,
          };
        } else {
          return item;
        }
      });

    case "COLOR_CHANGE":
      return prevState.map((item) => {
        if (item.id === action.id) {
          // 确定了要的项
          return {
            ...item,
            color: action.color,
          };
        } else {
          return item;
        }
      });

    default:
      return prevState;
  }
}

export default todosReducer;
